package com.yyxk.thousandtime.webutils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;


import com.yyxk.thousandtime.MainApplication;
import com.yyxk.thousandtime.bean.BaseBean;

import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * ----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * 项目名称：WheelMedical
 * 包名:com.yyxk.wheelmedical.webutils
 * 类描述：Retrofit设置，okHttp配置，加密解密以及错误code的统一处理类
 * 创建人：Random
 * 创建时间：11:17
 * 修改人：Random
 * 修改时间：11:17
 * 修改备注：
 */
public class RetrofitHelp {
    private static ResponseCallBack responseCallBack;
    private static ResponseCallBack drResponseCallBack;
    private static ResponseCallBack pResponseCallBack;
    private static final String BASE_URL = "https://59894d8c.ngrok.io";
    private static final String ALI_UPLOAD_URL = "http://adios.huerkang.cn/";
    public static String sUrl;


    private RetrofitHelp() {

    }

    /**
     * 单例模式创建responseCallBack
     *
     * @return
     */
    public static ResponseCallBack getResponseCallBack() {
        Retrofit builder = null;
        if (responseCallBack == null) {
            builder = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(getOkHttpClient())
                    .addConverterFactory(JsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
            responseCallBack = builder
                    .create(ResponseCallBack.class);

        }
        return responseCallBack;
    }

    /**
     * 单例模式创建responseCallBack
     *
     * @return
     */
    public static ResponseCallBack getUpLoadCallBack() {
        Retrofit builder = null;
        if (responseCallBack == null) {
            builder = new Retrofit.Builder()
                    .baseUrl(ALI_UPLOAD_URL)
                    .client(getOkHttpClient())
                    .addConverterFactory(JsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
            responseCallBack = builder
                    .create(ResponseCallBack.class);
        }
        return responseCallBack;
    }


    /**
     * 定制的okHttpClient
     * 在此重新构建RequestBody，包括传入日志，改变统一URL
     * 进行统一加密
     *
     * @return
     */
    private static OkHttpClient getOkHttpClient() {
        final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
        return client;
    }

    /**
     * 判断网络是否可用
     *
     * @return 布尔类型的值true false
     */
    public static boolean IsNetConnect() {
        ConnectivityManager manager = (ConnectivityManager) MainApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info == null) {
            return false;
        } else {
            return info.isConnected();
        }
    }

    private Handler mHandler = new Handler(Looper.getMainLooper());

    /**
     * 用来统一处理Http的Code,并将HttpResult的Data部分剥离出来返回给subscriber
     *
     * @param <T> Subscriber真正需要的数据类型，也就是Data部分的数据类型
     */
    public class HttpResultFunc<T> implements Func1<BaseBean<T>, T> {
        @Override
        public T call(BaseBean<T> httpResult) {
//            if (httpResult.getErrors() != null) {
//                Log.i("taggggggggg", "Error=" + httpResult.getErrors().getErrMsg());
//            }

//            if (!httpResult.isSuccess()) {
//                reMakeErrorData(httpResult);//重构data
//            }

//            if (httpResult.getData() != null) {
//                return httpResult.getData();
//            } else {
//                return httpResult.getDatas();
//            }
            return httpResult.getData();
        }
    }


    /**
     * 重构Data,如果Code不等于1，这时创建一个新的CodeBean交由ProgressSubscriber判断
     */
//    private void reMakeErrorData(BaseBean httpResult) {
//        httpResult.setData(new CodeBean().setSuccess(false).setErrors(httpResult.getErrors()));
//    }


    public static <T> void toSubscribe(Observable<T> o, Subscriber<T> s) {
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    }

    //在访问时创建单例
    private static class SingletonHolder {
        private static final RetrofitHelp INSTANCE = new RetrofitHelp();
    }


    //获取单例
    public static RetrofitHelp getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
